#!/usr/bin/python

import time
from PyQt4.QtCore import *
from api.client import *

REFRESH_TIME=5

class clientThread(QThread): 
    def __init__(self, ui, addr):
        QThread.__init__(self)
        self.vars = []
        self.ui = ui
        self.seguir = True
        self.connectat = False
        self.addr = addr

    def __del__(self):
        self.seguir = False
        if self.connectat:
           self.cliLector.desconnecta()

    def connectar(self):
	self.ui.statusbar.showMessage("Connectant amb %s:%d ..." % self.addr)
        try: 
           self.cliLector = ctrlLector(self.addr)
           self.connectat = True
        except Exception, err:
           raise 

        self.ui.statusbar.showMessage("Consultant estat ...")
        self.id = self.cliLector.getId()
	self.ui.statusbar.showMessage("Llegint configuracio ...")
        self.conf = self.cliLector.getConf()
        self.ui.statusbar.showMessage("Llegint definicions ...")
        self.defs = self.cliLector.getDefs()
	self.ui.statusbar.showMessage("Llegint variables ...")
        self.vars = self.cliLector.getVars()
    
        self.tempsRefresc = int(self.conf[1]['tempslectura'])/2 if int(self.conf[1]['tempslectura'])>0 else REFRESH_TIME

        if self.cliLector.started:
           self.ui.statusbar.showMessage("Servidor de lectures actiu i capturant dades ...")
           self.ui.actionConnectar.setEnabled(0)
           self.emit(SIGNAL("defColsHist()"))
        else:
           self.ui.statusbar.showMessage("Servidor de lectures actiu i esperant ...")
           self.ui.actionConnectar.setEnabled(1)
           self.ui.actionIniciar.setEnabled(1)
 
    def iniciar(self):
        if not self.cliLector.started:
           self.cliLector.start()
           time.sleep(1)
           self.vars = self.cliLector.getVars()
           self.emit(SIGNAL("defColsHist()"))
  
    def run(self):
	print "Thread running ..."
        while self.seguir:
              if self.cliLector.started:
		 self.vars = self.cliLector.getVars()
                 self.emit(SIGNAL("pintaVars()"))
              self.sleep(self.tempsRefresc)

        self.cliLector.desconnecta()
